package com.atsmart.app.handler;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.ImageView;

import com.atsmart.app.http.ImageLoader.ImageCallbak;

public class ImageLoadedHandler {
	private Handler handler = null;

	private static ImageLoadedHandler sImageLoaderHanler = new ImageLoadedHandler();

	public static ImageLoadedHandler getInstance() {
		return sImageLoaderHanler;
	}

	private class ImageLoadedInfo {
		public ImageView view_;
		public Bitmap bm_;
		public ImageCallbak callback_;

		public ImageLoadedInfo(ImageView view, Bitmap bm, ImageCallbak callback) {
			view_ = view;
			bm_ = bm;
			callback_ = callback;
		}
	}

	private ImageLoadedHandler() {

		handler = new Handler(Looper.getMainLooper()) {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				if (msg != null && msg.obj != null) {
					ImageLoadedInfo imageLoadedInfo = (ImageLoadedInfo) msg.obj;
					ImageView view = imageLoadedInfo.view_;
					if (view != null) {
						if (imageLoadedInfo.callback_ != null) {
							imageLoadedInfo.callback_.setResource(view,
									imageLoadedInfo.bm_);
						} else {
							view.setImageBitmap(imageLoadedInfo.bm_);
						}
					}
				}
			}
		};
	}

	public void notifyLoaded(ImageView view, Bitmap bitmap) {
		notifyLoaded(view, bitmap, null);
	}

	public void notifyLoaded(ImageView view, Bitmap bitmap, ImageCallbak callbak) {
		if (handler != null) {
			Message msg = handler.obtainMessage();
			msg.what = 1;
			msg.obj = new ImageLoadedInfo(view, bitmap, callbak);
			handler.sendMessage(msg);
		}
	}
}
